package com.chenjj.bigdata.solr.client.impl;


import com.chenjj.bigdata.solr.client.SolrClient;
import com.chenjj.bigdata.solr.client.SolrSort;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;

public class SolrCloudClientImpl implements SolrClient {
	private CloudSolrClient client = null;
	private Logger logger  = LoggerFactory.getLogger(getClass());
	@SuppressWarnings("unused")
	private SolrCloudClientImpl(){}

	/**
	 * 
	 * @param zkHost   ip:port,ip1:port,ip2:port/solr
	 * @param coreName
	 */
	public SolrCloudClientImpl(String zkHost,String coreName){
		if(zkHost.toLowerCase().startsWith("http")){
			throw new RuntimeException("can not create solr cloud client with :" + zkHost);
		}
		
		client = new CloudSolrClient(zkHost);
		client.setDefaultCollection(coreName);
	}
	
	
	@Override
	public void add(SolrInputDocument doc) {
		try {
			client.add(doc);
			client.commit();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}

	@Override
	public QueryResponse query(String q, String fq, int start, int rows,
                               String fl, String df,SolrSort sort) {
		 SolrQuery query = new SolrQuery();
		 query.set("q", q);
		 query.set("fq", fq);
		 query.setStart(start);
		 query.setRows(rows);
		 query.set("fl", fl);
		 query.set("df", df);
		 query.set("shards.tolerant","true");//只从存活的shards取数

         if(sort != null){
             query.setSort(sort.getSortField(),sort.getOrderBy());
         }

		try {
			return client.query(query);
		} catch (SolrServerException | IOException e) {
			logger.error("Solr query failed",e);
		}
		return null;
	}	
	
	public void close(){
		try {
			client.close();
		} catch (IOException e) {
			logger.error("close solr client failed ",e);
		}
	}

	@Override
	public void add(Collection<SolrInputDocument> docs) {
		try {
			client.add(docs);
			client.commit();
		} catch (SolrServerException | IOException e) {
			throw new RuntimeException(e);
		}
	}
	
}
